package hc.bre.rest.admin

import org.apache.shiro.SecurityUtils
import org.apache.shiro.authc.*
import org.apache.shiro.authc.credential.HashedCredentialsMatcher
import org.apache.shiro.authz.*
import org.apache.shiro.crypto.SecureRandomNumberGenerator
import org.apache.shiro.crypto.hash.Sha256Hash
import org.apache.shiro.realm.AuthorizingRealm
import org.apache.shiro.subject.PrincipalCollection
import org.apache.shiro.util.ByteSource
import org.springframework.beans.factory.annotation.Autowired

@groovy.transform.CompileStatic
public class AuthRealm extends AuthorizingRealm {
	@Autowired
	BreAdminService authService;
	
	//定义如何获取用户的角色和权限的逻辑，给shiro做权限判断
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		BreUser user = (BreUser) getAvailablePrincipal(principals);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//		info.setRoles(user.getRoles());
		info.setStringPermissions(user.getPerms());
		return info;
	}

	//定义如何获取用户信息的业务逻辑，给shiro做登录
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
		
		String usercode = ((UsernamePasswordToken) token).getUsername();
		BreUser user = authService.config.userList.find{usercode == it.code };
		return new SimpleAuthenticationInfo(user, user.password, getName());
	}

}

